from wordcloud import WordCloud
import os

class TextProcess:
    def __init__(self, dir):
        self.dir = dir
    def loadFile(self):
        with open(self.dir,'r',encoding='utf-8') as f:
            text = f.read()
        return text
    def splitWords(self,text):
        text = text.lower()
        for ch in '!"#$%&()*+,-./;:<=>?@[\\]^‘_{|}~\t\n':
            text = text.replace(ch,' ')
        words = text.strip().split(' ')
        while '' in words:
            words.remove('')
        return words
    def wordCount(self,words):
        word_dict={}
        for word in words:
            word_dict[word] = word_dict.get(word,0) + 1
        return word_dict
    def freqSort(self,dict,show=False):
        word_freq = sorted(word_count.items(), key = lambda d:d[1], reverse=True)
        if show == True:
            for w in word_freq:
                print(w[0]+':'+str(w[1]))
        return word_freq
    def wordCloud(self,word_freq,imgae_dir):
        if os.path.exists(imgae_dir):
            os.remove(imgae_dir)
        cloud_list = [' ']
        for w in word_freq:
            cloud_list.append(w[0])
        WordCloud(font_path='msyh.ttc',background_color='white',
        width=800,height=600,collocations=False).generate(text).to_file(imgae_dir)


if __name__ == "__main__":
    TP = TextProcess('2019kaoyan_text1.txt')
    text = TP.loadFile()
    # print(text)
    word_list = TP.splitWords(text)
    # print(word_list)
    word_count = TP.wordCount(word_list)
    # print(word_count)
    word_freq = TP.freqSort(word_count,show=True)
    TP.wordCloud(word_freq,'wordcloud1.png')
